package cn.keniykey.mc.landterritory.landview;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Nullable;

import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import cn.keniykey.mc.generallibrary.input.api.EInputResult;
import cn.keniykey.mc.generallibrary.input.api.IInputRequestManager;
import cn.keniykey.mc.generallibrary.input.api.IInputResultHandler;
import cn.keniykey.mc.landterritory.config.ConfigurationManager;
import cn.keniykey.mc.landterritory.config.LanguageManager;
import cn.keniykey.mc.landterritory.config.ViewsConfiguration;
import cn.keniykey.mc.landterritory.config.ViewsConfiguration.ViewConfig;
import cn.keniykey.mc.landterritory.event.LandFlagUpdateEvent;
import cn.keniykey.mc.landterritory.land.api.Land;
import cn.keniykey.mc.landterritory.land.api.LandUtil;
import cn.keniykey.mc.landterritory.landflag.LandFlag;
import cn.keniykey.mc.landterritory.landflag.api.ELandFlagParType;
import cn.keniykey.mc.landterritory.landflag.api.ILandFlagDetection;
import cn.keniykey.mc.landterritory.landflag.api.JavaLandFlag;
import cn.keniykey.mc.landterritory.landflag.api.LandFlagSetting;
import cn.keniykey.mc.landterritory.toolkit.Util;
import cn.keniykey.mc.viewlibrary.container.api.EContainerType;
import cn.keniykey.mc.viewlibrary.view.api.AbFrameView;
import cn.keniykey.mc.viewlibrary.view.api.FrameViewBundle;
import cn.keniykey.mc.viewlibrary.view.api.IViewClickHandler;
import cn.keniykey.mc.viewlibrary.view.api.ViewClickReport;
import cn.keniykey.mc.viewlibrary.view.api.template.AbChooseView;
import cn.keniykey.mc.viewlibrary.view.api.template.ChooseViewIntentBuilder;

public final class LandFlagInfoView extends AbLandFrameView{

	protected LandFlagInfoView(Player player1) {
		super(player1);
	}

	private static final String VIEW_NAME = "flaginfo";
	
	private static final int CODE_CHOOSE_ADDALL = 10100;
	private static final int CODE_CHOOSE_CLEAR = 10101;
	
	private Land land;
	private LandFlag landflag;

	@Override
	protected void onCreate() {
		super.onCreate();
		final FrameViewBundle bundle = this.getIntent().getExtras();
		this.land = bundle.getValue("land", null);
		this.landflag = bundle.getValue("landflag", null);
		
		final ViewConfig config_view = ViewsConfiguration.getViewConfig(VIEW_NAME);
		this.setViewType(EContainerType.matchContainer(config_view.getViewSize()));
		this.setTitle(Util.conver(config_view.getViewTitle()));
		
		this.setIconClick(config_view.getViewItemSlot("back"), config_view.getViewItem("back"), AbLandFrameView.CLICK_BACK);
		if(!ELandFlagParType.NONE.equals(this.landflag.getELandFlagParType())) {
			final int amount_par = LandViewUtil.getLandFlagParAmount(this.land, this.landflag);
			final int amount_max = LandViewUtil.getLandFlagParMaxAmount(this.landflag);
			if(amount_par < amount_max) {
				this.setIconClick(config_view.getViewItemSlot("add"), config_view.getViewItem("add"), new IViewClickHandler() {
					@Override
					public void onClick(Player player, AbFrameView view, ViewClickReport report) {
						if(!LandFlagInfoView.this.isMatchClickSpeed()) return;
						IInputRequestManager.getIInputRequestManager().requestInput(player, LandViewUtil.INPUT_COMMAND_STR, new IInputResultHandler() {
							@Override
							public boolean onInputResult(EInputResult result, OfflinePlayer offplayer, @Nullable String str) {
								boolean cancel = true;
								if(EInputResult.INPUT.equals(result)) {
									cancel = LandFlagInfoView.this.inputAddLandFlagPar(str);
								}
								if(cancel) LandFlagInfoView.this.finishAll();
								LandViewUtil.inputResultResponse(result, offplayer, cancel, 1101500);
								return cancel;
							}
						});
						view.hidden();
						player.sendMessage(LanguageManager.getChatLang(1101510, LandFlagInfoView.this.landflag.getDisplayName()));
					}
				});
			}
			if(amount_par > 0) {
				this.setIconClick(config_view.getViewItemSlot("remove"), config_view.getViewItem("remove"), new IViewClickHandler() {
					@Override
					public void onClick(Player player, AbFrameView view, ViewClickReport report) {
						if(!LandFlagInfoView.this.isMatchClickSpeed()) return;
						IInputRequestManager.getIInputRequestManager().requestInput(player, LandViewUtil.INPUT_COMMAND_STR, new IInputResultHandler() {
							@Override
							public boolean onInputResult(EInputResult result, OfflinePlayer offplayer, @Nullable String str) {
								boolean cancel = true;
								if(EInputResult.INPUT.equals(result)) {
									cancel = LandFlagInfoView.this.inputRemoveLandFlagPar(str);
								}
								if(cancel) LandFlagInfoView.this.finishAll();
								LandViewUtil.inputResultResponse(result, offplayer, cancel, 1101550);
								return cancel;
							}
						});
						view.hidden();
						player.sendMessage(LanguageManager.getChatLang(1101554, LandFlagInfoView.this.landflag.getDisplayName()));
					}
				});
				this.setIconClick(config_view.getViewItemSlot("clear"), config_view.getViewItem("clear"), new IViewClickHandler() {
					@Override
					public void onClick(Player player, AbFrameView view, ViewClickReport report) {
						if(!LandFlagInfoView.this.isMatchClickSpeed()) return;
						final ChooseViewIntentBuilder builder = new ChooseViewIntentBuilder(LandChooseView.class);
						builder.setChooseCountdown(ConfigurationManager.View_Choose_Countdown);
						builder.setCustomPromptName(LanguageManager.getLang(1101601, LanguageManager.getLang(1101650)));
						builder.setCustomPromptLore(Util.listFromStr(LanguageManager.getLang(1101602,
							LandViewUtil.getLandLabelStr(LandFlagInfoView.this.land), LandFlagInfoView.this.landflag.getDisplayName())));
						LandFlagInfoView.this.showViewForResult(builder.build(), CODE_CHOOSE_CLEAR);
					}
				});
			}
		}
		if(this.landflag.allowAllPlayerData()) {
			this.setIconClick(config_view.getViewItemSlot("addall"), config_view.getViewItem("addall"), new IViewClickHandler() {
				@Override
				public void onClick(Player player, AbFrameView view, ViewClickReport report) {
					if(!LandFlagInfoView.this.isMatchClickSpeed()) return;
					final ChooseViewIntentBuilder builder = new ChooseViewIntentBuilder(LandChooseView.class);
					builder.setChooseCountdown(ConfigurationManager.View_Choose_Countdown);
					builder.setCustomPromptName(LanguageManager.getLang(1101601, LanguageManager.getLang(1101600)));
					builder.setCustomPromptLore(Util.listFromStr(LanguageManager.getLang(1101602,
							LandViewUtil.getLandLabelStr(LandFlagInfoView.this.land), LandFlagInfoView.this.landflag.getDisplayName())));
					LandFlagInfoView.this.showViewForResult(builder.build(), CODE_CHOOSE_ADDALL);
				}
			});
		}
	}
	@Override
	protected void onShowBefore() {
		super.onShowBefore();
		final ViewConfig config_view = ViewsConfiguration.getViewConfig(VIEW_NAME);
		ItemStack item = config_view.getViewItem("about");
		ItemMeta meta = item.getItemMeta();
		meta.setDisplayName(meta.getDisplayName() + this.landflag.getDisplayName());
		final StringBuilder builder_str = new StringBuilder(LanguageManager.getLang(1101000, this.landflag.getName(),
				LanguageManager.getLang(this.landflag.getELandFlagParType().getLandID())));
		final List<String> indulist = this.landflag.getIntroductionLore();
		if(indulist != null && !indulist.isEmpty()) {
			builder_str.append("\n").append(LanguageManager.getLang(1101001));
			for(final String str_indu : indulist) {
				builder_str.append("\n ").append(str_indu);
			}
		}
		if(this.land.getFlags().containsKey(this.landflag.getName())) {
			final Set<String> set_parameters = this.land.getFlags().get(this.landflag.getName());
			if(!set_parameters.isEmpty()) {
				builder_str.append("\n").append(LanguageManager.getLang(1101002));
				if(set_parameters.contains(JavaLandFlag.ALL_PAR_STR)) {
					builder_str.append("\n").append(LanguageManager.getLang(1003000));
				}else {
					int length = 0;
					for(final String str : set_parameters) {
						builder_str.append((0 == length ? "\n " : "§e, "));
						builder_str.append("§r").append(str);
						length++;
						if(length > 4) length = 0; //一行最多5个参数显示
					}
				}
			}
		}
		meta.setLore(Util.listFromStr(builder_str.toString()));
		item.setItemMeta(meta);
		this.setIcon(config_view.getViewItemSlot("about"), item);
	}
	
	@Override
	protected void onViewResult(int requestcode, int resultcode, @Nullable FrameViewBundle bundle) {
		super.onViewResult(requestcode, resultcode, bundle);
		switch(AbChooseView.EChooseResult.muchResult(resultcode)) {
		case CONFIRM:
			if(CODE_CHOOSE_ADDALL == requestcode) {
				this.addLandFlagAllPar();
				break;
			}
			if(CODE_CHOOSE_CLEAR == requestcode) {
				this.clearLandFlagAllPar();
				break;
			}
			this.getPlayer().sendMessage(LanguageManager.getChatLang(1001001) + requestcode);
			break;
		case VETO:
			return;
		default:
		}
		this.finishAll();
	}
	
	private boolean inputAddLandFlagPar(@Nullable String str) {
		final Player player = this.getPlayer();
		if(str == null || str.isEmpty()) {
			player.sendMessage(LanguageManager.getChatLang(1101501, LanguageManager.getLang(1101500)));
			return false;
		}
		if(str.equals(JavaLandFlag.ALL_PAR_STR)) {
			player.sendMessage(LanguageManager.getChatLang(1101503, LanguageManager.getLang(1101500)));
			return false;
		}
		if(str.length() > ConfigurationManager.View_FlagInfo_ContentLimit) {
			player.sendMessage(LanguageManager.getChatLang(1101505, str.length(), ConfigurationManager.View_FlagInfo_ContentLimit));
			return false;
		}
		if(this.land.isDeleted()) return true;
		final LandFlag landflag = LandFlagInfoView.this.landflag;
		if(!JavaLandFlag.hasLandFlag(this.land, landflag)) {
			player.sendMessage(LanguageManager.getChatLang(1101504, landflag.getDisplayName(), LandViewUtil.getLandLabelStr(this.land)));
			return true;
		}
		final int amount_par = LandViewUtil.getLandFlagParAmount(this.land, landflag);
		final int amount_max = LandViewUtil.getLandFlagParMaxAmount(landflag);
		if(amount_par >= amount_max) {
			player.sendMessage(LanguageManager.getChatLang(1101506, amount_par, amount_max));
			return true;
		}
		if(!LandUtil.hasLandPermission(player, this.land, LandViewUtil.getLandFLagMinPermissionLevel(landflag))) {
			player.sendMessage(LanguageManager.getChatLang(1005000, LanguageManager.getLang(1101500)));
			return true;
		}
		final String flagname = landflag.getName();
		Set<String> landflag_pars = this.land.getFlags().get(flagname);
		if(landflag_pars.isEmpty()) {
			landflag_pars = new HashSet<>();
			this.land.getFlags().put(flagname, landflag_pars);
		}
		if(!landflag_pars.add(str.toLowerCase())) {
			player.sendMessage(LanguageManager.getChatLang(1101507, str));
			return false;
		}
		try {
			final ILandFlagDetection dete_update = LandFlagSetting.getUpdateDetection(flagname);
			if(dete_update != null && !dete_update.onRequest(player, this.land)) {
				landflag_pars.remove(str.toLowerCase());
				if(landflag_pars.isEmpty()) this.land.getFlags().put(flagname, Collections.emptySet());
				player.sendMessage(LanguageManager.getChatLang(1101508, LandViewUtil.getLandLabelStr(this.land),
						landflag.getDisplayName(), str));
				return true;
			}
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		this.land.updateFlags();
		Bukkit.getPluginManager().callEvent(new LandFlagUpdateEvent(player, this.land, landflag));
		player.sendMessage(LanguageManager.getChatLang(1101509, LandViewUtil.getLandLabelStr(this.land),
				landflag.getDisplayName(), str));
		return true;
	}
	private boolean inputRemoveLandFlagPar(@Nullable String str) {
		final Player player = this.getPlayer();
		if(str == null || str.isEmpty()) {
			player.sendMessage(LanguageManager.getChatLang(1101501, LanguageManager.getLang(1101550)));
			return false;
		}
		if(str.equals(JavaLandFlag.ALL_PAR_STR)) {
			player.sendMessage(LanguageManager.getChatLang(1101503, LanguageManager.getLang(1101550)));
			return false;
		}
		if(str.length() > ConfigurationManager.View_FlagInfo_ContentLimit) {
			player.sendMessage(LanguageManager.getChatLang(1101505, str.length(), ConfigurationManager.View_FlagInfo_ContentLimit));
			return false;
		}
		if(this.land.isDeleted()) return true;
		final LandFlag landflag = LandFlagInfoView.this.landflag;
		if(!JavaLandFlag.hasLandFlag(this.land, landflag)) {
			player.sendMessage(LanguageManager.getChatLang(1101504, landflag.getDisplayName(), LandViewUtil.getLandLabelStr(this.land)));
			return true;
		}
		if(!LandUtil.hasLandPermission(player, this.land, LandViewUtil.getLandFLagMinPermissionLevel(landflag))) {
			player.sendMessage(LanguageManager.getChatLang(1005000, LanguageManager.getLang(1101500)));
			return true;
		}
		final int amount_par = LandViewUtil.getLandFlagParAmount(this.land, landflag);
		final int amount_max = LandViewUtil.getLandFlagParMaxAmount(landflag);
		if(amount_par >= amount_max) {
			player.sendMessage(LanguageManager.getChatLang(1101506, amount_par, amount_max));
			return true;
		}
		final String flagname = landflag.getName();
		if(!this.land.getFlags().containsKey(flagname)) {
			player.sendMessage(LanguageManager.getChatLang(1101551, str));
			return true;
		}
		Set<String> landflag_pars = this.land.getFlags().get(flagname);
		if(landflag_pars.isEmpty() || !landflag_pars.remove(str.toLowerCase())) {
			player.sendMessage(LanguageManager.getChatLang(1101551, str));
			return false;
		}
		try {
			final ILandFlagDetection dete_update = LandFlagSetting.getUpdateDetection(flagname);
			if(dete_update != null && !dete_update.onRequest(player, this.land)) {
				landflag_pars.add(str.toLowerCase());
				player.sendMessage(LanguageManager.getChatLang(1101552, LandViewUtil.getLandLabelStr(this.land),
						landflag.getDisplayName(), str));
				return true;
			}
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		if(landflag_pars.isEmpty()) this.land.getFlags().put(flagname, Collections.emptySet());
		this.land.updateFlags();
		Bukkit.getPluginManager().callEvent(new LandFlagUpdateEvent(player, this.land, landflag));
		player.sendMessage(LanguageManager.getChatLang(1101553, LandViewUtil.getLandLabelStr(this.land),
				landflag.getDisplayName(), str));
		return true;
	}
	private void addLandFlagAllPar() {
		if(this.land.isDeleted()) return;
		final Player player = this.getPlayer();
		if(!JavaLandFlag.hasLandFlag(this.land, this.landflag)) {
			player.sendMessage(LanguageManager.getChatLang(1101504, this.landflag.getDisplayName(), LandViewUtil.getLandLabelStr(this.land)));
			return;
		}
		if(!LandUtil.hasLandPermission(player, this.land, LandViewUtil.getLandFLagMinPermissionLevel(this.landflag))) {
			player.sendMessage(LanguageManager.getChatLang(1005000, LanguageManager.getLang(1101600)));
			return;
		}
		final String flagname = this.landflag.getName();
		Set<String> pars = this.land.getFlags().get(flagname);
		if(!pars.contains(JavaLandFlag.ALL_PAR_STR)) {
			final ILandFlagDetection dete_update = LandFlagSetting.getUpdateDetection(flagname);
			if(dete_update != null) {
				final Set<String> pars_backup;
				if(pars.isEmpty()) {
					pars_backup = Collections.emptySet();
					pars = new HashSet<>();
				}else {
					pars_backup = new HashSet<>(pars);
					pars.clear();
				}
				pars.add(JavaLandFlag.ALL_PAR_STR);
				try {
					if(!dete_update.onRequest(player, this.land)) {
						if(pars_backup.isEmpty()) {
							this.land.getFlags().put(flagname, Collections.emptySet());
						}else {
							pars.clear();
							pars.addAll(pars_backup);
						}
						player.sendMessage(LanguageManager.getChatLang(1101508, LandViewUtil.getLandLabelStr(this.land),
								this.landflag.getDisplayName(),LanguageManager.getLang(1003000)));
						return;
					}
				}catch(Exception ex) {
					ex.printStackTrace();
				}
			}else {
				if(pars.isEmpty()) {
					pars = new HashSet<>();
					this.land.getFlags().put(flagname, pars);
				}else {
					pars.clear();
				}
				pars.add(JavaLandFlag.ALL_PAR_STR);
			}
			this.land.updateFlags();
			Bukkit.getPluginManager().callEvent(new LandFlagUpdateEvent(player, this.land, this.landflag));
		}
		player.sendMessage(LanguageManager.getChatLang(1101509, LandViewUtil.getLandLabelStr(this.land),
				this.landflag.getDisplayName(), LanguageManager.getLang(1003000)));
		
	}
	private void clearLandFlagAllPar() {
		if(this.land.isDeleted()) return;
		final Player player = this.getPlayer();
		if(!JavaLandFlag.hasLandFlag(this.land, this.landflag)) {
			player.sendMessage(LanguageManager.getChatLang(1101504, this.landflag.getDisplayName(), LandViewUtil.getLandLabelStr(this.land)));
			return;
		}
		if(!LandUtil.hasLandPermission(player, this.land, LandViewUtil.getLandFLagMinPermissionLevel(this.landflag))) {
			player.sendMessage(LanguageManager.getChatLang(1005000, LanguageManager.getLang(1101600)));
			return;
		}
		final String flagname = this.landflag.getName();
		if(this.land.getFlags().containsKey(flagname)) {
			final Set<String> pars = this.land.getFlags().remove(flagname);
			final ILandFlagDetection dete_update = LandFlagSetting.getUpdateDetection(flagname);
			if(dete_update != null) {
				try {
					if(!dete_update.onRequest(player, this.land)) {
						this.land.getFlags().put(flagname, pars);
						player.sendMessage(LanguageManager.getChatLang(1101552, LandViewUtil.getLandLabelStr(this.land),
								this.landflag.getDisplayName(),LanguageManager.getLang(1003000)));
						return;
					}
				}catch(Exception ex) {
					ex.printStackTrace();
				}
			}
			pars.clear();
			this.land.updateFlags();
			Bukkit.getPluginManager().callEvent(new LandFlagUpdateEvent(player, this.land, this.landflag));
		}
		player.sendMessage(LanguageManager.getChatLang(1101651, LandViewUtil.getLandLabelStr(this.land),
				this.landflag.getDisplayName()));
	}
}